package com.example.seabedmusic.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.example.seabedmusic.entity.Song;

import java.util.ArrayList;
import java.util.List;

public class LocalMusicScanner {
    private static final String TAG = "LocalMusicScanner";

    public static List<Song> scanLocalMusic(Context context) {
        List<Song> localSongs = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();

        // 首先检查权限
        if (!PermissionManager.hasRequiredPermissions(context)) {
            Log.w(TAG, "无存储权限，无法扫描本地音乐");
            return localSongs;
        }

        // 定义要查询的列
        String[] projection = {
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.ALBUM_ID
        };

        // 查询条件：音乐文件且时长大于30秒（过滤短音频）
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0 AND " +
                MediaStore.Audio.Media.DURATION + " >= 30000";

        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

        Cursor cursor = null;
        try {
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            cursor = contentResolver.query(uri, projection, selection, null, sortOrder);

            if (cursor != null && cursor.moveToFirst()) {
                int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
                int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
                int artistColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                int albumColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                int durationColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
                int dataColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
                int albumIdColumn = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);

                do {
                    String id = cursor.getString(idColumn);
                    String title = cursor.getString(titleColumn);
                    String artist = cursor.getString(artistColumn);
                    String album = cursor.getString(albumColumn);
                    long duration = cursor.getLong(durationColumn);
                    String filePath = cursor.getString(dataColumn);

                    // 处理未知艺术家
                    if (artist == null || artist.equals("<unknown>")) {
                        artist = "未知艺术家";
                    }

                    // 处理无标题
                    if (title == null || title.isEmpty()) {
                        // 从文件路径提取文件名作为标题
                        if (filePath != null) {
                            int lastSlash = filePath.lastIndexOf('/');
                            if (lastSlash != -1 && lastSlash + 1 < filePath.length()) {
                                title = filePath.substring(lastSlash + 1);
                                // 移除文件扩展名
                                int dotIndex = title.lastIndexOf('.');
                                if (dotIndex != -1) {
                                    title = title.substring(0, dotIndex);
                                }
                            } else {
                                title = "未知歌曲";
                            }
                        } else {
                            title = "未知歌曲";
                        }
                    }

                    // 创建本地音乐对象
                    Song song = new Song(id, title, artist, album, duration, filePath);
                    song.setLocal(true);
                    localSongs.add(song);

                    Log.d(TAG, "找到本地音乐: " + title + " - " + artist + " | 路径: " + filePath);

                } while (cursor.moveToNext());
            } else {
                Log.w(TAG, "未找到本地音乐文件或游标为空");
            }

            Log.d(TAG, "共找到 " + localSongs.size() + " 首本地音乐");

        } catch (SecurityException e) {
            Log.e(TAG, "权限不足，无法访问媒体库", e);
            throw e; // 重新抛出异常，让调用者处理
        } catch (Exception e) {
            Log.e(TAG, "扫描本地音乐失败", e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return localSongs;
    }
}